//
//  YTStudyDetailsViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/11/20.
//

#import "YTStudyDetailsViewController.h"
#import "YTStashTJModel.h"
#import <WebKit/WebKit.h>
@interface YTStudyDetailsViewController()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UINavigationControllerDelegate,UIScrollViewDelegate,NSURLSessionDelegate>

@property (nonatomic ,strong) YTStashTJModel * model;
//@property (nonatomic ,strong) UIScrollView * scrollView;
@property (nonatomic,strong)WKWebView *webView;
@property (nonatomic,strong)UIView * topview;
@property (nonatomic,strong)WKWebViewConfiguration *config;
@end

@implementation YTStudyDetailsViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView * topview = [UIView new];
    topview.backgroundColor = KcolorHex(@"#0967FF");
    self.topview = topview;
    [self.view addSubview:topview];
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(Knav_HeightX);
    }];
    MJWeakSelf
    UIView * backview = [UIView new].addClickBlock(^{
        [weakSelf back];
    });
    [topview addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.left.bottom.offset(0);
        make.width.offset(kwt(140));
    }];
    
    UIImageView * leftimg = kimageView(@"white_path");
    [backview addSubview:leftimg];
    [leftimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(20);
        make.left.offset(kwt(10));
        make.centerY.offset(0);
    }];
    
    UILabel * leftlab = [DTKTool labelWithText:@"详情" andFont:kCFont(19) andTextColor:UIColor.whiteColor];
    [backview addSubview:leftlab];
    [leftlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(kwt(45));
    }];
 
//    UIScrollView * scrollView = [UIScrollView new];
//    self.scrollView = scrollView;
//    [self.view addSubview:scrollView];
//    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.bottom.right.equalTo(self.view);
//        make.top.equalTo(topview.mas_bottom);
//    }];
    [self loadNewData];
    
}


- (WKWebView *)webView
{
    if(_webView == nil)
    {
        
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource: @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);" injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        

//        [self.web_view loadRequest:[NSURLRequest requestWithURL:_url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0]];
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        self.config = config;
        // 创建设置对象
        WKPreferences *preference = [[WKPreferences alloc]init];
        //最小字体大小 当将javaScriptEnabled属性设置为NO时，可以看到明显的效果
//        preference.minimumFontSize = 0;
        //设置是否支持javaScript 默认是支持的
        preference.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示是否允许不经过用户交互由javaScript自动打开窗口
        preference.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences = preference;
        
        // 是使用h5的视频播放器在线播放, 还是使用原生播放器全屏播放
        config.allowsInlineMediaPlayback = YES;
        //设置视频是否需要用户手动播放  设置为NO则会允许自动播放
        config.mediaTypesRequiringUserActionForPlayback = YES;
        //设置是否允许画中画技术 在特定设备上有效
        config.allowsPictureInPictureMediaPlayback = YES;
        //设置请求的User-Agent信息中应用程序名称 iOS9后可用
        config.applicationNameForUserAgent = @"ChinaDailyForiPad";
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
   
//        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0,-20,kScreenWidth,kScreenHeight+20)];
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:config];
//        _webView.frame = self.view.bounds;
        [self.view addSubview:self.webView];
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(0);
            make.top.equalTo(self.topview.mas_bottom);
            make.right.mas_offset(0);
            make.bottom.mas_offset(0);
        }];

        _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        _webView.opaque = NO;
        _webView.scrollView.bounces = NO;
//        _webView.scrollView.delegate = self;

     }
    
    return _webView;
}


- (void)loadNewData{
    [self.view showBusyHUD];
    
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:self.ID forKey:@"id"];
    [SCNetManger learnInfoEditDetailWithDict:dict andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            self.model = [YTStashTJModel yy_modelWithDictionary:model.result];
            
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
- (void)setModel:(YTStashTJModel *)model{
    
  
    
    _model = model;
   
    [self.webView loadHTMLString:[self adaptWebViewForHtml:[NSString stringWithFormat:@"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><h3>%@</h3><p style=\"color:#7D7D7D\">%@</p >%@",model.title,model.scheduledTime,model.imageText]] baseURL:nil];
    
//    UIView *contentView = [[UIView alloc] init];
//    [self.scrollView addSubview:contentView];
//    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.scrollView);
//        make.width.offset(SCREEN_WIDTH);
//    }];
//    
//    UILabel * title = [DTKTool labelWithText:model.title andFont:kCFont(18) andTextColor:KcolorHex(@"#222222")];
//    title.numberOfLines = 0;
//    [contentView addSubview:title];
//    [title mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.offset(kwt(24));
//        make.left.offset(kwt(15));
//        make.right.offset(kwt(-15));
//    }];
//    UILabel * createTime = [DTKTool labelWithText:model.createTime andFont:kFont(15) andTextColor:KcolorHex(@"#7D7D7D")];
//    [contentView addSubview:createTime];
//    [createTime mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(title.mas_bottom).offset(kwt(10));
//        make.left.offset(kwt(15));
//        make.right.offset(kwt(-15));
//    }];
//    
//    UILabel * content = [DTKTool labelWithText:model.imageText andFont:kFont(17) andTextColor:KcolorHex(@"#222222")];
//    content.attributedText = [DTKTool AttributedStringWithStr:model.imageText andNodeColor:KcolorHex(@"#222222") andSeledColor:KcolorHex(@"#222222") andFont:kFont(17) andPattenr:@""];
//    content.numberOfLines = 0;
//    [contentView addSubview:content];
//    [content mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(createTime.mas_bottom).offset(kwt(24));
//        make.left.offset(kwt(15));
//        make.right.offset(kwt(-15));
//        make.bottom.equalTo(contentView.mas_bottom).offset(kwt(-20));
//    }];
//    
//    if([model.displayForm isEqualToString:@"1"]){//1:视频
//        
//    } else if([model.displayForm isEqualToString:@"2"]){//2:图文
//        
//    }
    
    //    self.scrollView
}
//HTML适配图片文字
- (NSString *)adaptWebViewForHtml:(NSString *) htmlStr {
    NSMutableString *headHtml = [[NSMutableString alloc] initWithCapacity:0];
    [headHtml appendString : @"<html>" ];
    [headHtml appendString : @"<head>" ];
    [headHtml appendString : @"<meta charset=\"utf-8\">" ];
    [headHtml appendString : @"<meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=false\" />" ];
    [headHtml appendString : @"<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />" ];
    [headHtml appendString : @"<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />" ];
    [headHtml appendString : @"<meta name=\"black\" name=\"apple-mobile-web-app-status-bar-style\" />" ];
    //适配图片宽度，让图片宽度等于屏幕宽度
    //[headHtml appendString : @"<style>img{width:100%;}</style>" ];
    //[headHtml appendString : @"<style>img{height:auto;}</style>" ];
    //适配图片宽度，让图片宽度最大等于屏幕宽度
//    [headHtml appendString : @"<style>img{max-width:100%;width:auto;height:auto;}</style>"];
    //适配图片宽度，如果图片宽度超过手机屏幕宽度，就让图片宽度等于手机屏幕宽度，高度自适应，如果图片宽度小于屏幕宽度，就显示图片大小
    [headHtml appendString : @"<script type='text/javascript'>"
     "window.onload = function(){\n"
     "var maxwidth=document.body.clientWidth;\n" //屏幕宽度
     "for(i=0;i <document.images.length;i++){\n"
     "var myimg = document.images[i];\n"
     "if(myimg.width > maxwidth){\n"
     "myimg.style.width = '100%';\n"
     "myimg.style.height = 'auto'\n;"
     "}\n"
     "}\n"
     "}\n"
     "</script>\n"];
    [headHtml appendString : @"<style>table{width:100%;}</style>" ];
    [headHtml appendString : @"<title>webview</title>" ];
    NSString *bodyHtml;
    bodyHtml = [NSString stringWithString:headHtml];
    bodyHtml = [bodyHtml stringByAppendingString:htmlStr];
    return bodyHtml;
}
@end
